#coding=utf-8
'''
    家对象定义
'''
import logging, traceback
from tornado.escape import json_encode, json_decode
import util
import const
from mysqlHelper import mysql
import time
#import datetime
from user import UserManager
from store import store
from bar_order import BarOrderManager
import task
class home(util.SingleClass):
    
    def __init__(self):
        pass
    
    #进入房间
    @staticmethod
    def enter_house(request, data):
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}
        #得到用户基本信息
        userinfo = user.m_userinfo
        uid = userinfo['uid']
        #进房间扣除勇气值        
        
        #房主uid
        roomer_uid = data['owner']
        is_roomer = True
        if uid!=roomer_uid:
            is_roomer = False
        #如果当前用户不是房主则扣除当前用户勇气值
        if not is_roomer:
            if not util.CountUserUtil.judgeAndEditExt('enter_house', request, uid, "visit_room")  :
                return False
            #--记录拜访----拜访总数加一
            UserManager.updateLogTotalHomeVisite()
        
        #得到房主的记录信息
        roomer = UserManager.get_userinfo_by_col(roomer_uid, "a.uid,a.nickname,a.birthday,a.height,a.sex,a.province,a.city,a.country,\
        b.level,b.charm,b.my_clothing,b.my_ornament,b.my_present,b.my_furniture ,b.my_props, b.assets,b.my_bodyinfo,\
        c.last_clean,c.clean,c.room_gold,c.my_visit_rec,c.guest_visit_rec, c.guest_steal_rec")
       
        if not roomer:           
            return {"res":"user_is_null"}        
        else:
            roomer['birthday'] = str(roomer['birthday'])
            roomer['age']=UserManager.countAge(roomer['birthday'])
        #得到房主可以被偷的钱
        roomer_gold = home.get_roomer_can_steal_gold(roomer.get('room_gold'),is_roomer)
 
        can_steal_gold = roomer_gold.get('can_steal_gold') #可取得的利息
        tmp_total_left_gold = roomer_gold.get('rest_gold') #最大利息
        tmp_gold_level = roomer_gold.get('level')
        tmp_gold_status = roomer_gold.get('gold_status')
        tmp_gold_rest = roomer_gold.get('rest')
        #得当当前用户的记录信息
        if is_roomer:
            userinfo = roomer.copy()
        else:
            userinfo = UserManager.get_userinfo_record(uid, 'uid,nickname,my_visit_rec')
         
        #判断是否偷过
        res = {}
        tmpStrIsSteal = "no"    #是否偷过钱 "yes/no"
        last_all_rec = roomer['guest_steal_rec']
        nowtime = time.strftime('%Y-%m-%d') 
        if last_all_rec:
            last_all_rec = json_decode(last_all_rec)
            tmpLogList = last_all_rec.get('log')
            if tmpLogList:
                for v in tmpLogList:
                    td = str(v['timeline'])[0:10]                                
                    if v['uid'] == uid and td == nowtime :
                        tmpStrIsSteal = "yes"
                        break
         
        #如果当前用户为房主则无其它操作，获取房主的资产值并返回到客户端
        if is_roomer:
            res['res'] = True    
            res['clean'] = home.get_roomer_clean(roomer)                                  #清洁度
            res['assets'] = home.get_roomer_assets(roomer, uid ,res['clean'])             #资产值
            res['roomer_uid'] = roomer_uid                                                #房主的UID
            res['left_roomer_gold'] = can_steal_gold                                   #剩余金币数
            res['total_roomer_gold'] =  tmp_total_left_gold                            #总金币数
            res['gold_level'] =  tmp_gold_level                                        #存钱罐等级
            res['gold_status'] = tmp_gold_status                                       #存钱罐状态，是否存钱中
            res['gold_rest'] = tmp_gold_rest                                       #利息
            res['age']=roomer['age']
            res['province']=roomer['province']
            res['city']=roomer['city']
            res['nickname']=roomer['nickname']
            res['height']=roomer['height']
            res['sex']=roomer['sex']
            res['level']=roomer['level']
            res['charm']=roomer['charm']           
            if roomer['my_bodyinfo']:
                res['my_bodyinfo']=json_decode(roomer['my_bodyinfo'])
            else:
                res['my_bodyinfo']={}
            
            res['is_steal'] = tmpStrIsSteal
            return res
        
        #设置当前访问记录
        new_dic = {'got':0, 'msg':'拜访了房间'}
        #如果房主有访问记录则在访问记录上追加新纪录
        if(roomer['guest_visit_rec']):
            roomer_rec = json_decode(roomer['guest_visit_rec'])
            if roomer_rec.has_key('log'):
                log = roomer_rec['log']
                #组合访问记录到数组中
                list = home.get_user_log(log, None, None, 'uid')
                #如果当前用户今天访问了10次则增加房主数值
                u_list = []
                for v in list:
                    if v['got'] == 0:                        
                        u_list.append(v)    
                tmpCount =const.Config_visited_get_charm_limit()
                                           
                if len(u_list) >= tmpCount:               
                    i = 0
                    for vv in u_list:
                        if i==tmpCount:
                            break
                        if vv['got'] == 0: 
                            log.remove(vv)
                            vv['got'] = 1
                            log.append(vv)                            
                        i+=1
                                                 
                    roomer_rec['log'] = log
                    roomer['guest_visit_rec'] = json_encode(roomer_rec)
                    util.CountUserUtil.judgeAndEditExt('enter_house', None, roomer_uid, "visited_room")                    
#                    conn.upData('t_user_data',data,"WHERE uid = %d"%roomer_uid,1)
         
        UserManager.set_user_rec(userinfo, roomer, 'guest_visit_rec', const.Config_vist_max_rec(), new_dic)#设置房主的访客记录
        res = UserManager.set_user_rec(roomer, userinfo, 'my_visit_rec', const.Config_vist_max_rec())#设置我的访问记录
               
        res['is_steal'] = tmpStrIsSteal
        
        res['clean'] = home.get_roomer_clean(roomer)
        res['assets'] = home.get_roomer_assets(roomer, uid, res['clean'])
        res['roomer_uid'] = roomer_uid
        res['left_roomer_gold'] = can_steal_gold
        res['total_roomer_gold'] =  tmp_total_left_gold                            #总金币数
        res['gold_level'] =  tmp_gold_level                                        #存钱罐等级
        res['gold_status'] = tmp_gold_status                                       #存钱罐状态，是否存钱中
        res['gold_rest'] = tmp_gold_rest                                       #利息
        res['age']=roomer['age']
        res['province']=roomer['province']
        res['city']=roomer['city']
        res['nickname']=roomer['nickname']
        res['height']=roomer['height']
        res['sex']=roomer['sex']    
        res['level']=roomer['level']
        res['charm']=roomer['charm']    
        if roomer['my_bodyinfo']:
            res['my_bodyinfo']=json_decode(roomer['my_bodyinfo'])
        else:
            res['my_bodyinfo']={}
        return res
    
    @staticmethod
    def get_roomer_clean(roomer):
        '''获取房间的清洁度'''
        uid = roomer['uid']
        last_clean = roomer['last_clean']
        clean = int(roomer['clean'])      
        nottime = int(time.time())       
        if last_clean:            
            last_time = time.mktime(time.strptime(str(last_clean), '%Y-%m-%d %H:%M:%S'))
        else:
            last_clean = time.strftime('%Y-%m-%d %H:%M:%S') 
            last_time = nottime    
        #计算上次打算距离现在多少天
        tmpDays =  int((nottime - last_time)/const.Config_clean_time())
        #如果房主是第一次进房间则初始化清洁度
        if int(nottime - last_time)==0:
            if not clean:
                clean = const.Config_clean_max()
            conn = mysql()
            conn.upData('t_user_record', {"clean":clean,"last_clean":last_clean}, "WHERE uid = %d"%uid,asyn=True)
            return clean
        #上次打算时间距离现在超过一天，则扣除清洁度    
    
        if tmpDays>0:       
            clean  = clean - int(int(const.Config_clean_dem())*tmpDays)
        
            if clean<=0:
                clean=0
            conn = mysql()        
            conn.upData('t_user_record', {"clean":clean,"last_clean":time.strftime('%Y-%m-%d %H:%M:%S') }, "WHERE uid = %d"%uid,asyn=True)
      
        return clean
        
    
    #获取房主资产值             房主信息，查看人uid
    @staticmethod
    def get_roomer_assets(roomer, uid, clean):
  
        price = 0
        price = home.get_my_goods_price(roomer['my_clothing'], price)
        price = home.get_my_goods_price(roomer['my_ornament'], price)
        price = home.get_my_goods_price(roomer['my_present'], price)
        price = home.get_my_goods_price(roomer['my_furniture'], price)
        price = home.get_my_goods_price(roomer['my_props'], price)  
        price = int(price * 1.0 * clean /100.0)
        conn = mysql()
        #更新我的资产值
        conn.upData('t_user_data', {'assets':price }," WHERE uid = %d" %uid)
        UserManager.update_user(uid, {'assets':price})
        return price
        
    #获取我的商品价值
    @staticmethod
    def get_my_goods_price(rec, price=0):
        if not rec:
            return price
        rec = json_decode(rec)
        
        for k, v in  rec.iteritems():            
            for kk, vv in v.iteritems():                
                for vvv in vv['info']:
                    if vvv:      
                        price = price + store.get_one_of_my_goods_value(vvv)     
        return price                
    

    
    #穿戴衣服
    @staticmethod
    def save_my_bodyinfo(request, data):
        '''去掉过期服装，统计当前所有服装魅力，并更新到内存和数据库中'''
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}
        conn = mysql()
       
        tmpUser = user
        userinfo = user.m_userinfo
        uid = userinfo['uid']
        goods = data['goods']
        
        charm = 0
        energy = 0
        courage = 0
        power = 0
        quality = 0
        
        exp_goods=[]
        for v in goods:
            goods_id = v['id']
            
            rec_id = v['rec_id']
            if rec_id<0 or goods_id < 0:                
                continue
            
            inlay_id = v.get('inlay_id')
            goods_info = store.get_goods_info(goods_id)#得到当前商品信息
            
            my_goods_info = store.get_my_goods_info(uid, goods_info)#根据当前商品得到我的穿着信息
            if not my_goods_info:
                return {"res":'not_goods'} 
            
            my_goods_list = my_goods_info.get('my_goods_list')#当前分类的我的商品列表（精确到三级类）
           
            my_goods = my_goods_info.get('my_goods')#我的所有商品（一级类）
            
            
            last_my_goods_info = store.get_my_goods_info_by_rec_id(rec_id, my_goods_list)#根据当前记录id从我的商品列表中取得当前商品
           
            if not last_my_goods_info:
                return {"res":'not_goods'} 
            
            #如果过期了则并且不是无限制商品则脱掉
            if last_my_goods_info.get('limit_time')<int(time.time()) and last_my_goods_info.get('limit_time')>0:
                exp_goods_list = {}
                exp_goods_list['id'] = goods_id
                exp_goods_list['rec_id'] = rec_id
                exp_goods.append(exp_goods_list)
                goods.remove(v)
                continue
            
            inlay_info = {}
            inlay_info['charm']=0
            inlay_info['energy']=0
            inlay_info['courage']=0
            inlay_info['power']=0
            inlay_info['quality']=0
            
            #镶嵌信息
            if last_my_goods_info.has_key('inlay'):
                if last_my_goods_info['inlay']['inlay_id'] != inlay_id:#如果我衣服上的镶嵌ID不等于要佩戴的镶嵌ID，则表示改变了镶嵌信息，需更新我的服装信息     
                    if inlay_id:
                        inlay_info = store.get_goods_info(inlay_id)
                        if not inlay_info:
                            return {"res":'not_inlay'} 
                    inlay_rec_id = v['inlay_rec_id']
                    if not inlay_rec_id:
                        return {"res":'not_inlay'}
                    if not inlay_id:
                        inlay_rec_id = 0
                    dict = {"inlay":{'inlay_id':inlay_id, 'rec_id':inlay_rec_id}}
                    res = store.set_goods_info(uid, rec_id, goods_info, my_goods_info, dict)
                    if res["res"] != True:
                        return res                
            #得到当前服装魅力值
            charm   +=  goods_info['charm']   + inlay_info['charm']       
            energy  +=  goods_info['energy']  + inlay_info['energy']  
            courage +=  goods_info['courage'] + inlay_info['courage']  
            power   +=  goods_info['power']   + inlay_info['power']  
            quality +=  goods_info['quality'] + inlay_info['quality']  
        
        #差值
        demCharm = int(charm - home.getUserWear(userinfo.get('my_bodyinfo'),'charm'))
        demEnergy= int(energy - home.getUserWear(userinfo.get('my_bodyinfo'), 'energy'))
        demCourage= int(courage - home.getUserWear(userinfo.get('my_bodyinfo'), 'courage'))
        demPower = int(power - home.getUserWear(userinfo.get('my_bodyinfo'), 'power'))
        demQuality = int(quality - home.getUserWear(userinfo.get('my_bodyinfo'), 'quality'))
        
        #如果当前穿着的商品和历史商品不一致，需要修改内存和数据库
       
        #更新我的穿着魅力
#        conn.upData('t_user_data', {'my_bodyinfo':json_encode(data),                                    
#                                    'energy':(userinfo.get('energy')+demEnergy),
#                                    'courage':(userinfo.get('courage')+demCourage),
#                                    'power':(userinfo.get('power')+demPower),
#                                    'quality':(userinfo.get('quality')+demQuality),
#                                    'charm':(userinfo.get('charm')+demCharm),
#                                    'cloth_charm':charm},
#                                     "WHERE uid = %d" %uid)
#        UserManager.update_user(uid, {'my_bodyinfo':data,
#                                      'energy':(userinfo.get('energy')+demEnergy),
#                                      'courage':(userinfo.get('courage')+demCourage),
#                                      'power':(userinfo.get('power')+demPower),
#                                      'quality':(userinfo.get('quality')+demQuality),
#                                      'charm':(userinfo.get('charm')+demCharm),
#                                      'cloth_charm':charm
#                                      })

        tmpDataDict = {}
        tmpDataDict['my_bodyinfo'] = json_encode(data)                                
        tmpDataDict['energy'] = (tmpUser.getUserInfoToInt('energy')+demEnergy)
        tmpDataDict['courage'] = (tmpUser.getUserInfoToInt('courage')+demCourage)
        tmpDataDict['power'] = (tmpUser.getUserInfoToInt('power')+demPower)
        tmpDataDict['quality'] = (tmpUser.getUserInfoToInt('quality')+demQuality)
        tmpDataDict['charm'] = (tmpUser.getUserInfoToInt('charm')+demCharm)
        tmpDataDict['cloth_charm'] = charm
        conn.upData('t_user_data', tmpDataDict, "WHERE uid = %d" %uid)
        
        tmpDataDict["my_bodyinfo"] = data
        UserManager.update_user(uid, tmpDataDict)

        if exp_goods:
            tmpContent = '你有%s件衣服过期'%len(exp_goods)
            UserManager.pushBasicSysInfo(tmpContent, uid)
            #UserManager.pushSysInfoToSomebody('sys_info', tmpContent, None, uid)
            
         #judgeAndEdit(cmd='set_clothing', request=request, uid=uid, bJudge=False,  charm=charm, cloth_charm=charm)
        
        #---道具装饰类的穿戴使用---
        import process_props
        process_props.usePropsAttire(user)
        
#        return {"res":True, "user":{'energy':userinfo.get('energy'),
#                                    'courage':userinfo.get('courage'),
#                                    'power':userinfo.get('power'),
#                                    'quality':userinfo.get('quality'),                                    
#                                    'charm':userinfo.get('charm'),
#                                    'cloth_charm':charm}, 
#                                    "goods":goods,
#                                    "exp_goods":exp_goods}

        tmpDataDict.pop('my_bodyinfo')
        return {"res":True, "user":tmpDataDict, "goods":goods, "exp_goods":exp_goods}
    
    #获取我身上穿着的数值
    @staticmethod
    def getUserWear(my_bodyinfo,col):
        goods = my_bodyinfo.get('goods')
        tmpValue = 0
        if goods:
            for v in goods:
                goods_info = store.get_goods_info(v['id']) 
                if goods_info:
                    val = goods_info.get(col)
                    if val:
                        tmpValue = tmpValue + val
        return tmpValue
    
        
    #摆放家具
    @staticmethod
    def set_furniture(request, data):
        ''''''
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}
        userinfo = user.m_userinfo#得到我的基本资料
        uid = userinfo['uid']
        goods = data['goods']
        for v in goods:
            goods_id = v.get('id')
            rec_id = v.get('rec_id')
            if not rec_id or not goods_id:
                continue
               
            x = v['x']
            y = v['y']
            z = v['z']
            goods_info = store.get_goods_info(goods_id)
            if not goods_info:
                continue
                
            my_goods_info = store.get_my_goods_info(uid, goods_info)
            if not my_goods_info:
                continue
            dic = {"x":x, "y":y, "z":z}
            res = store.set_goods_info(uid, rec_id, goods_info, my_goods_info, dic)
            if res["res"] != True:
                return res
            
        return {"res":True}   


    #打扫房间
    @staticmethod
    def clean_house(request, data):
        '''打扫房间'''
        tmpUser = UserManager.get_user_by_request(request)
        if not tmpUser:
            return {'res':'user_is_null'}       
        if tmpUser.m_current_place != 'house':
            return {'res':'not_in_house'}
        userinfo = tmpUser.m_userinfo
        uid = userinfo['uid']        
        nickname = userinfo['nickname']
        roomer_uid = data['uid']        
        roomer = UserManager.get_userinfo_record(roomer_uid, 'uid,nickname,last_clean,clean,guest_clean_rec')   
        userinfo = UserManager.get_userinfo_record(uid, 'uid,nickname,my_clean_rec')   
        #得到房主现在的清洁度
        if not roomer:
            return {'res':'user_is_null'}   
        
        now_clean = roomer['clean']
       
        #如果现在的清洁度大于等于最大清洁度，则不需要打扫
        if now_clean >= const.Config_clean_max():
            return {'res':'already_clean','clean':now_clean}
        if now_clean + const.Config_clean_add() > const.Config_clean_max():
            add = const.Config_clean_max() - now_clean
        else:
            add = const.Config_clean_add()
        #打扫房间增加用户属性
        if not util.CountUserUtil.judgeAndEditExt('clean_house', request, uid, "clean_house") :
            return False   
        #--记录打扫----打扫总数加一
        UserManager.updateLogTotalHomeClean()        
       
        if(roomer['guest_clean_rec']):
            roomer_rec = json_decode(roomer['guest_clean_rec'])
            if roomer_rec.has_key('log'):
                log = roomer_rec['log']
                #房主被打扫指定次数加魅力
                tmpCount = const.Config_roomer_get_charm_by_clean()
                u_list = []
                for v in log:
                    if v['got'] == 0:                        
                        u_list.append(v)
                              
                if len(u_list) >= tmpCount:   
                    i = 0                   
                    for vv in u_list:
                       
                        if i==tmpCount:
                            break
                        if vv['got'] == 0: 
                            log.remove(vv)
                            vv['got'] = 1
                            log.append(vv)                            
                        i+=1
                                           
                    roomer_rec['log'] = log                  
                    roomer['guest_clean_rec'] = json_encode(roomer_rec)
                    #如果被打算次数有10此则增加房主魅力
                    util.CountUserUtil.judgeAndEditExt('clean_house', None, roomer_uid, "House_be_clean")
        res = {"res":True}
        if uid != roomer_uid:   
            col2 = " last_clean='%s',clean = clean +'%s'" % (time.strftime('%Y-%m-%d %H:%M:%S'), add)
            new_dic = {"msg":"给你打扫了房间",'got':0}
            UserManager.set_user_rec(userinfo, roomer, 'guest_clean_rec', const.Config_clean_max(), new_dic, col2)#设置房主的访客打扫记录
        
            new_dic = {"msg":"给%s打扫了房间"%(roomer['nickname'])}
            res = UserManager.set_user_rec(roomer, userinfo, 'my_clean_rec', const.Config_clean_max(), new_dic)#设置我的打扫记录
            
            #添加成功则执行任务
            task.taskManager.do_task(tmpUser,'day_task','clean_house',roomer_uid)
        else:
            conn = mysql()
            tmpUpdata = {'last_clean':time.strftime('%Y-%m-%d %H:%M:%S'),'clean' : int(now_clean + add)}
            conn.upData('t_user_record', tmpUpdata, "WHERE uid = %d" %uid, asyn=True) 
            
        res['add_clean'] = add
        res['clean'] = now_clean + add
        return res
    
    #获得初始化房主存钱罐金币
    @staticmethod
    def get_roomer_config_steal_gold(level):
        return 0       
    
    #得到房主当天可以偷的钱
    @staticmethod
    def get_roomer_can_steal_gold(roomer_gold,is_roomer=True):  
        nowtime = int(time.time())   
        init_roomer_gold = {"gold":0,#剩余总利息
                           "addgold":0,#添加的金币
                           "addtime":0,#添加时间
                           "endtime":0,#结束时间
                           "level":1,#存钱罐等级
                           "rest":1,#利息1%
                           "can_steal_gold":0,#可取得利息
                           "rest_gold":0#最大利息
                           }      
        if not roomer_gold:             
            roomer_gold = init_roomer_gold.copy()
        else:
            roomer_gold = json_decode(roomer_gold)
            if not roomer_gold:                
                roomer_gold = init_roomer_gold.copy()
            elif not roomer_gold.has_key('addgold'):
                roomer_gold = init_roomer_gold.copy()
            else:
                tmpAddGold = roomer_gold.get('addgold')
                tmpAddtime = roomer_gold.get('addtime')
                tmpEndtime = roomer_gold.get('endtime')
                tmpLevel   = roomer_gold.get('level')
                tmpGold    = roomer_gold.get('gold')
                roomer_gold['rest_gold']=0
                if tmpAddGold>0 :
                    tmpSaveHour = int(int(nowtime - tmpAddtime)/60/60)   #当前存钱的总时长
                    tmpInHour = int(int(tmpEndtime - tmpAddtime)/60/60)  #预计存钱的总时长
                    
                    tmpTotalGold = int(tmpAddGold*home.getSaveGoldRest(tmpLevel)*tmpInHour)      #预计存钱总收入   
                    roomer_gold['rest']=int(home.getSaveGoldRest(tmpLevel)*100)
                    roomer_gold['rest_gold']=tmpTotalGold
                    if tmpSaveHour <tmpInHour:
                        tmpNowTotalGold = int(tmpAddGold*home.getSaveGoldRest(tmpLevel)*tmpSaveHour) #当前存钱总收入   
                    else:
                        tmpNowTotalGold = tmpTotalGold
                        
                    tmpCanStealGold = 0
                                    
                    if nowtime<tmpEndtime:#访客只能在存钱期限到期后偷钱
                        if is_roomer!=True  :
                            tmpCanStealGold = 0   
                        else:
                            tmpCanStealGold = int(tmpNowTotalGold *util.ConfigManager.getConfigLogic('Config_steal_gold_in_savetime')/100) 
                        if not tmpGold:
                            tmpGold = tmpTotalGold
                            roomer_gold['gold']=tmpGold               
                    else:   #到了取钱期限后，如果gold为0，则gold为   总收入tmpTotalGold
                        if not tmpGold:
                            tmpGold = tmpTotalGold
                            roomer_gold['gold']=tmpGold 
                                              
                        if not is_roomer  :#如果是游客，则按比例取，当利息剩下至总利息50%的时候不能再取                            
                            tmpCanStealGold = tmpGold - int(tmpTotalGold*0.5)
                            if tmpCanStealGold<=0:
                                tmpCanStealGold=0
                            else:
                                if tmpCanStealGold - int(tmpGold*const.Config_steal_gold()/100)>0:
                                    tmpCanStealGold = int(tmpGold*const.Config_steal_gold()/100)
                                else:
                                    tmpCanStealGold = 0
                        else:
                            tmpCanStealGold = roomer_gold['gold']
                            
                    roomer_gold['can_steal_gold'] = tmpCanStealGold
                else :
                    roomer_gold['can_steal_gold'] = 0
        roomer_gold['gold_status']=0
        if roomer_gold.get('addgold'):            
            roomer_gold['gold_status']=1
            if nowtime> roomer_gold.get('endtime'):
                roomer_gold['status']=2 
        return roomer_gold
    
    @staticmethod
    def getSaveGoldRest(level):
        '''获取存钱罐的利息'''
        if level<10:
            tmpRest = 0.01
        if level>=10:
            tmpRest = 0.02
        if level>=20:
            tmpRest = 0.04
        return  tmpRest  
            
        
    
    #偷钱
    @staticmethod
    def steal_gold(request, data):
        tmpUser = UserManager.get_user_by_request(request)
        if not tmpUser:
            return {'res':'user_is_null'}
        if tmpUser.m_current_place != 'house':
            return {'res':'not_in_house'}
			
        cmd = "steal_gold"
        userinfo = tmpUser.m_userinfo
        uid = userinfo['uid']
        roomer_uid = data['uid']
        
        is_roomer=True
        if uid!=roomer_uid:
            is_roomer=False
            task.taskManager.do_task(tmpUser,'first','first_steal_gold',roomer_uid)
        
        #获取房主偷钱和被偷钱记录
        roomer = UserManager.get_userinfo_by_col(roomer_uid, 'a.uid,a.nickname,b.level,c.room_gold,c.my_steal_rec,c.guest_steal_rec')
        
        if not roomer:
            return {"res":"user_is_null"}
        
        #得到房主可以被偷的钱
        roomer_gold = home.get_roomer_can_steal_gold(roomer['room_gold'],is_roomer)
        print roomer_gold
         #得到房主存钱罐的可以被偷的金币，即利息
        can_steal_gold = roomer_gold['can_steal_gold']     
         
        if can_steal_gold <= 0 and not is_roomer:            
            if roomer_gold.get('addgold')>0:
                return {"res":"roomer_saving_gold"}
            if roomer_gold.get('gold')<=0:
                return {"res":"roomer_no_gold"}
            else:
                return {"res":"roomer_less_gold"}
       
        #如果当前用户不是房主则查询当前用户是否投过钱,有偷过就退出
        nowtime = time.strftime('%Y-%m-%d') 
        if not is_roomer:            
            userinfo = UserManager.get_userinfo_record(uid, 'uid,nickname,my_steal_rec')
            last_all_rec = roomer['guest_steal_rec']
            if last_all_rec:
                last_all_rec = json_decode(last_all_rec)
                for v in last_all_rec['log']:
                    td = str(v['timeline'])[0:10]                                
                    if v['uid'] == uid and td == nowtime :
                        return {"res":"is_steal"}
                    
            #偷别人的钱， 需扣数值
            if not util.CountUserUtil.judgeAndEditExt(cmd, request, uid, "steal_gold", bPushErrorMsg=False):
    			return {"res":"not_quality_steal_gold"}
   
            new_dic = {"gold":can_steal_gold, 'msg':'偷了%s金币' % can_steal_gold}
            
        conn = mysql()
       
        
        if not is_roomer:
            tmpLogicMapObj = util.ConfigManager.getLogicInfo("default_logic")           #获取默认配置项
            util.ConfigManager.setLogicInfoVal_Gold(tmpLogicMapObj, can_steal_gold)     #金币
            util.CountUserUtil.judgeAndEditExt(cmd, request, uid, tmpLogicMapObj)       #加钱
            roomer_gold['gold'] = roomer_gold['gold'] - can_steal_gold
            UserManager.set_user_rec(userinfo, roomer, 'guest_steal_rec', const.Config_steal_max_rec(), new_dic, "room_gold='%s'" % json_encode(roomer_gold))#设置房主的访客记录和存钱罐余额
            res = UserManager.set_user_rec(roomer, userinfo, 'my_steal_rec', const.Config_steal_max_rec(), new_dic)#设置我的偷钱记录
            if res.get('res')==True:
            	#添加成功则执行任务
                task.taskManager.do_task(tmpUser,'day_task','steal_gold',roomer_uid)
                
        else:           
            #把存的钱还给用户
            tmpLogicMapObj = util.ConfigManager.getLogicInfo("default_logic")                       #获取默认配置项
            util.ConfigManager.setLogicInfoVal_Gold(tmpLogicMapObj, int(roomer_gold.get('addgold')+can_steal_gold))     #金币
            util.CountUserUtil.judgeAndEditExt(cmd, request, uid, tmpLogicMapObj)                   #加钱
            roomer_gold['gold']=0
            roomer_gold['addgold']=0
            roomer_gold['addtime']=0
            roomer_gold['endtime']=0           
            conn.upData('t_user_record', {"room_gold":json_encode(roomer_gold)}, "WHERE uid = %d"%roomer_uid)
            res = {"res":True}
            
            #res = UserManager.set_user_rec(userinfo, roomer, 'my_steal_rec', const.Config_steal_max_rec(), new_dic)#设置我的偷钱记录            
           
        return res
    
    @staticmethod
    def save_gold(request,data):
        '''存钱'''
        tmpUser = UserManager.get_user_by_request(request)
        if not tmpUser:
            return {'res':'user_is_null'}            
        cmd = "save_gold"
        userinfo = tmpUser.m_userinfo
        uid = userinfo['uid']
        tmpAddGold  = data.get('add_gold')
        tmpAddtime  = int(time.time())
        tmpSaveHour = data.get('hours')
        tmpEndtime  = tmpAddtime+tmpSaveHour*60*60
        
        if userinfo.get('gold')<tmpAddGold:
            return {'res':'not_gold'}
        
        roomer = UserManager.get_userinfo_record(uid, "room_gold")
        if not roomer:
            return {'res':'user_is_null'}     
        room_gold = home.get_roomer_can_steal_gold(roomer.get('room_gold'),True)
        if room_gold.get('addgold')>0:
            return {'res':'gold_is_saved'}
        
        tmpLogicMapObj = util.ConfigManager.getLogicInfo("default_logic")           #获取默认配置项
        util.ConfigManager.setLogicInfoVal_Gold(tmpLogicMapObj, -tmpAddGold)        #金币
        util.CountUserUtil.judgeAndEditExt(cmd, request, uid, tmpLogicMapObj)       #扣钱
        
        init_roomer_gold = {"gold":0,
                           "addgold":tmpAddGold,
                           "addtime":tmpAddtime,
                           "endtime":tmpEndtime,
                           "level":1,
                           "rest":1,
                           "can_steal_gold":0
                           }  
        conn = mysql()
        conn.upData('t_user_record', {'room_gold':json_encode(init_roomer_gold)}, "WHERE uid = %d"%uid)
        return {"res":True}
    
    @staticmethod
    def EditStealGold(tmpGold, tmpUID):        
        '''修改可被偷的钱数量''' 
        return
        tmpStealGoldTime = time.strftime('%Y-%m-%d')  
        tmpDict = {"gold": tmpGold, "addtime":tmpStealGoldTime}
        conn = mysql()
        conn.upData("t_user_record", {"room_gold":json_encode(tmpDict)}, " where uid = %s " % tmpUID,asyn=True)
     
    @staticmethod
    def EditStealGoldByLevel(tmpLevel, tmpUID):
        '''修改可被偷的钱数量''' 
        return
        tmpGold = home.get_roomer_config_steal_gold(tmpLevel)
        home.EditStealGold(tmpGold, tmpUID) 
        
        
    #创建相册
    @staticmethod
    def add_album(request, data):
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}

        userinfo = user.m_userinfo
        uid = userinfo['uid']
        aname = data['aname']
        #aname= eval("r'%s'" % aname)  
        role = data['role']
        album_id = data['album_id']
        
        userinfo = UserManager.get_userinfo_record(uid, 'photo_rec')
        rec = userinfo['photo_rec']
        last_rec_id = 1
        if rec:
            rec = json_decode(rec)
            if rec.has_key('a'):
                last_rec_id = rec['a']['last_rec_id'] + 1
            else:
                rec['a'] = {"last_rec_id":last_rec_id, "list":[]}
        
        else:
            rec = {"a":{"last_rec_id":last_rec_id, "list":[]}}
        
        if album_id:
            last_rec_id = album_id
            for v in rec['a']['list']:
                if v['rec_id'] == album_id:
                    rec['a']['list'].remove(v)
            
        new_rec = {"rec_id":last_rec_id, "cover":0, "aname":aname, "role":data['role'], "desc":data['desc'], "timeline":int(time.time())}
        
        rec['a']['list'].append(new_rec)
        rec['a']['last_rec_id'] = last_rec_id
        conn = mysql()       
        photo_rec = json_encode(rec)        
        conn.upData('t_user_record', {'photo_rec':photo_rec}, "WHERE uid =%d "%uid, asyn=True)   
#        conn.query(sql)
        return {"res":True}
            
    #获取相册列表 col=a表示查询相册  col=p 相片列表  c评论列表
    @staticmethod
    def get_album(request, data, col):    
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}
        uid = data['owner']
        begin = data['begin']
        nums = data['nums']
        #得到用户的相册记录
        userinfo = UserManager.get_userinfo_record(uid, 'photo_rec')
        if not userinfo:
            return {'res':'user_is_null'}
        rec = userinfo['photo_rec']
        if not rec:
            return {'res':True, col:{'list':[]}}
        rec = json_decode(rec)
        if not rec.has_key(col):
            return {'res':True, col:{'list':[]}}
        
        #查询相册列表
        if col == 'a':
            return_list = rec[col]['list']
            #如果有相册，但是没相片，则返回空列表
            if  rec.get('p'):
                if not rec['p'].get('list'):
                    return {'res':True, col:{'list':[]}}
            else:
                return {'res':True, col:{'list':[]}}
        
        #查询相片列表        
        if col == 'p':
            album_id = int(data['album_id'])
            return_list = []
            for v in rec[col]['list']:
                if v['album_id'] == album_id:
                    return_list.append(v)
        
        #查询评论列表
        if col == 'c':
            photo_id = int(data['photo_id'])
            return_list = []
            for v in rec[col]['list']:
                if v['photo_id'] == photo_id:
                    return_list.append(v)
        if not return_list:
            return {'res':True, col:{'list':[]}}
        rec[col]['list'] = return_list[begin - 1:begin - 1 + nums]
        return {'res':True, col:rec[col]}
        
    #相片评论
    @staticmethod
    def add_photo_comment(request, data):
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}
        userinfo = user.m_userinfo
        uid = userinfo['uid']
        nickname = userinfo['nickname']
        owner = data['owner']
        if uid == owner:
            return {'res':'not_comment_self'}
        comment = data['comment']
        photo_id = data['photo_id']
        comment_id = 0       
        userinfo = UserManager.get_userinfo_record(owner, 'photo_rec')
        rec = userinfo['photo_rec']
        last_rec_id = 1
        if not rec:
            return {'res':'user_no_p'}
        rec = json_decode(rec)
        if not rec.has_key('p'):
            return {'res':'user_no_p'}
        
        photo_list = rec['p']['list']
        if not photo_list:
            return {'res':'user_no_p'} 
        
        rs = store.get_my_goods_info_by_rec_id(photo_id, photo_list)
        if rs:
            rec['p']['list'].remove(rs)
        if comment == 1:
            rs['c_true'] = rs['c_true'] + 1
        else:
            rs['c_false'] = rs['c_false'] + 1
        rs['c_count'] = rs['c_count'] + 1
        rec['p']['list'].append(rs)   

        if rec.has_key('c'):
            last_rec_id = rec['c']['last_rec_id'] + 1
            for v in rec['c']['list']:
                if v['uid'] == uid:
                    return {'res':'user_commented'}
        else:
            rec['c'] = {"last_rec_id":last_rec_id, "list":[]} 
            
        #评论相片给评论者增加和减少相应属性
        if not util.CountUserUtil.judgeAndEditExt('photo_leave_words', request, uid, "comment_photo"):
            return {'res':'not_courage'}
            
        new_rec = {"rec_id":last_rec_id, "comment_id":comment_id, "photo_id":photo_id, "uid":uid, "nickname":nickname, "msg":data['comment'], "timeline":int(time.time())}       
        rec['c']['list'].append(new_rec)
       
        rec['c']['last_rec_id'] = last_rec_id
        conn = mysql()       
        photo_rec = json_encode(rec)        
        conn.upData("t_user_record", {'photo_rec':photo_rec}, " WHERE uid =%d " % owner,asyn=True)         
        return {"res":True}
    
    
    #相册审核
    @staticmethod
    def verify_user_photo(request,data):
        owner = data.get('owner')
        album_id = data.get('album_id')
        photo_id = data.get('photo_id')
        tmpType = data.get('type')
        #查询用户历史的相片
        userinfo = UserManager.get_userinfo_record(owner, 'photo_rec')
        if not userinfo:
            return {'res':'user_is_null'}        
        rec = userinfo['photo_rec']
        if not rec:
            return {'res':'user_no_p'}
        rec = json_decode(rec)            
        if not rec.has_key('p'):
            return {'res':'user_no_p'}        
        photo_list = rec['p']['list']
        if not photo_list:
            return {'res':'user_no_p'}
        
        
        
            
        tmpPhotoRec = store.get_my_goods_info_by_rec_id(photo_id, photo_list)
        photo_list.remove(tmpPhotoRec)
        
        #'none', 'admit', 'warning', 'delete', 'advise'
        if tmpType!='delete':
            tmpPhotoRec['type'] = tmpType
            photo_list.append(tmpPhotoRec)
        
        #保存到数据库
        conn = mysql()       
        photo_rec = json_encode(rec)
       
        conn.upData("t_user_record", {'photo_rec':photo_rec}, " WHERE uid =%d " % owner, asyn=True) 
        
        #更新用户数值
        #util.CountUserUtil.judgeAndEditExt('verify_user_photo', None, owner, "verify_user_photo_%s"%tmpType)
        return {"res":True}       
        
    
    
    #留言
    @staticmethod
    def send_memo(request, data):
        tmpUser = UserManager.get_user_by_request(request)
        if not tmpUser:
            return {'res':'user_is_null'}
        userinfo = tmpUser.m_userinfo
        uid = userinfo['uid']     
        title = data.get('title')
        content = data.get('content')
        right = data.get('right')       
        roomer_uid = data.get('owner')
        #留言扣除属性     
        if right == 0:   
            if not util.CountUserUtil.judgeAndEditExt('send_memo', request, uid, "leave_msg"):
                return {"res":"not_courage"}            
        else:
            if not util.CountUserUtil.judgeAndEditExt('send_memo', request, uid, "leave_p_msg"):
                return {"res":"not_courage"}
            
        roomer = UserManager.get_userinfo_record(roomer_uid, 'uid,nickname,guest_leaveword')
        
        
        userinfo = UserManager.get_userinfo_record(uid, 'uid,nickname,my_leaveword')        
        
        new_dic = {'title':title, 'content':content, 'right':right, 'got':0}
        if(roomer['guest_leaveword']):
            roomer_rec = json_decode(roomer['guest_leaveword'])
            if roomer_rec.has_key('log'):
                log = roomer_rec['log']
                list = home.get_user_log(log, None, None, None)
                u_list = []
                for v in list:
                    if v.get('right') == right:                        
                        u_list.append(v)
                if right==0:    
                    tmpCount = const.Config_left_mgs_get_limit()
                    tmpAddConst = 'left_msg'
                if right==1:
                    tmpCount = const.Config_left_personnel_mgs_get_limit()
                    tmpAddConst = 'left_personnel_msg'
                
                if (len(u_list)+1) % tmpCount==0:
                    #如果访问有10此则增加房主魅力
                    util.CountUserUtil.judgeAndEditExt('send_memo', None, roomer_uid, tmpAddConst) 
        
        UserManager.set_user_rec(userinfo, roomer, 'guest_leaveword', const.Config_leave_max(), new_dic)#设置房主的访客记录
        res = UserManager.set_user_rec(roomer, userinfo, 'my_leaveword', const.Config_leave_max(), new_dic)#设置我的访问记录
        
        #发一条系统消息通知对方
        tmpSendType = 'send_memo'
        if right==0:
            tmpSendMsg = '留言'
        else:
            tmpSendMsg = '私信'
        tmpContent = '您有一条%s'%tmpSendMsg
        tmpNoticeDict = {
                        'right':right,
                        'title':title,
                        'content':content,
                        'timeline':time.strftime('%Y-%m-%d %H:%M:%S'),
                        'got':0,
                        'nickname':userinfo.get('nickname'),
                        'id':[]
                        }              
        tmpContentAddtion = tmpNoticeDict        
        UserManager.pushSysInfoToSomebody(tmpSendType, tmpContent, tmpContentAddtion, *tuple([roomer_uid]))    
        
        return res
        
    #查询留言
    @staticmethod
    def get_msg(request, data):
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}
        userinfo = user.m_userinfo
        uid = userinfo['uid']
        tmpType = data.get('type')
        roomer_uid = data.get('owner')
        begin = data.get('begin')
        nums = data.get('nums')
        if not nums:
            nums = 300
        act = data.get('act')
        if act =='send':
            col_pre = 'my'
        else:
            col_pre = 'guest'
        #查询房主留言    
        if tmpType == 1:
            col = '%s_leaveword'%col_pre             
            roomer = UserManager.get_userinfo_record(roomer_uid, col)
            if not roomer:
                return {'res':'user_is_null'}                  
                
            if not roomer.get(col):
                return {"res":True, "list":[],"total":0}
            rec = json_decode(roomer[col])            
            return_log = []
            for v in rec['log']:
                #print v['right']
                if v['right'] == 0:
                    v['rectype']= '%s_leaveword'%col_pre               
                    return_log.append(v)   
            return_log= util.sortArrDict(return_log , 'timeline', 'desc')
            return {"res":True, "list":return_log[begin - 1:begin - 1 + nums],"total":len(return_log)}
        #查询活跃记录
        if tmpType == 2:
            col = '%s_visit_rec,%s_steal_rec ,%s_clean_rec,%s_leaveword,impression '%(col_pre,col_pre,col_pre,col_pre)
            roomer = UserManager.get_userinfo_record(roomer_uid, col)
            log1 = []
            if roomer['%s_visit_rec'%col_pre]:               
                rec1 = json_decode(roomer['%s_visit_rec'%col_pre])
                tmpLog1 = rec1['log']
                if tmpLog1:
                    for v in tmpLog1:
                        tmpDic = v                        
                        tmpDic['rectype'] = '%s_visit_rec'%col_pre
                        log1.append(tmpDic);
                        
            log2 = []
            if roomer['%s_steal_rec'%col_pre]:               
                rec2 = json_decode(roomer['%s_steal_rec'%col_pre])
                tmpLog2 = rec2['log']
                if tmpLog2:
                    for v in tmpLog2:
                        tmpDic = v                        
                        tmpDic['rectype'] = '%s_steal_rec'%col_pre
                        log2.append(tmpDic);
                        
            log3 = []
            if roomer['%s_clean_rec'%col_pre]:               
                rec3 = json_decode(roomer['%s_clean_rec'%col_pre])               
                tmpLog3 = rec3['log']
                if tmpLog3:
                    for v in tmpLog3:
                        tmpDic = v                        
                        tmpDic['rectype'] = '%s_clean_rec'%col_pre
                        log3.append(tmpDic);
               
            log4 = []
            if roomer['%s_leaveword'%col_pre]:               
                rec4 = json_decode(roomer['%s_leaveword'%col_pre])
                tmpLog4 = rec4['log']
                if tmpLog4:
                    for v in tmpLog4:
                        tmpDic = {}
                        tmpDic['uid'] = v['uid']
                        tmpDic['timeline'] = v['timeline']
                        tmpDic['rec_id'] = v['rec_id']
                        tmpDic['msg'] = '给你留言了'
                        tmpDic['nickname'] = v['nickname']
                        tmpDic['rectype'] = '%s_leaveword'%col_pre
                        log4.append(tmpDic);
            
            log5 = []
            if roomer.get('impression'):               
                rec5 = json_decode(roomer.get('impression'))
                if rec5:
                    tmpLog5 = rec5['log']
                    if tmpLog5:
                        for v in tmpLog5:
                            tmpDic = {}
                            tmpDic['uid'] = v['uid']
                            tmpDic['timeline'] = v['timeline']
                            tmpDic['rec_id'] = v['rec_id']
                            tmpDic['msg'] = '评论了相片'
                            tmpDic['nickname'] = v['nickname']
                            tmpDic['rectype'] = 'impression'
                            log5.append(tmpDic);
                
            return_log = log2 + log3 + log4 +log5
            if log1:
                log1 = util.sortArrDict(log1,'timeline','desc');
            if return_log:
                return_log = util.sortArrDict(return_log,'timeline','desc');
            return_log = log1+return_log
            return {"res":True, "list":return_log[begin - 1:begin - 1 + nums],"total":len(return_log)}
        #查询私信
        if tmpType == 3: 
            col = col_pre +'_leaveword' 
            roomer = UserManager.get_userinfo_record(roomer_uid, col)                 
            if not roomer[col]:
                return {"res":True, "list":[],"total":0}            
            rec = json_decode(roomer[col])            
            return_log = []
            for v in rec['log']:
                if v['right'] == 1 or  v['right'] == 2:
                    v['rectype'] = col_pre +'_leaveword' 
                    return_log.append(v)
                        
            return_log = util.sortArrDict(return_log , 'timeline', 'desc')
            return {"res":True, "list":return_log[begin - 1:begin - 1 + nums],"total":len(return_log)}
   
    #查询用户活跃记录
    @staticmethod
    def get_act_msg(request, data):
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}
        
        uid = data['owner']
        rec = UserManager.get_user_game_info(uid)
        bar = BarOrderManager()
        user_order = bar.getOrder(user)
        rec['order'] = user_order
        return {"res":True, "user":rec}
        
    
    #删除相册、相片、评论
    @staticmethod
    def del_album(request, data):
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}
        userinfo = user.m_userinfo
        uid = userinfo['uid']
        rec_id = data['id']
        col = data['type']
        #根据删除的类型取得当前类型对应的列表{"p":{"list":[{}]}}
        if col == 0:
            col = 'a'#相册
        if col == 1:
            col = 'p'#相片
        if col == 2:
            col = 'c'#评论
        userinfo = UserManager.get_userinfo_record(uid, 'photo_rec')
        if not userinfo['photo_rec']:
            return {'res':'user_no_%s' % col}
        rec = json_decode(userinfo['photo_rec'])
        if not rec.has_key(col):
            return {'res':'user_no_%s' % col}
        have_k = 0
        for v in rec[col]['list']:
            if v['rec_id'] == rec_id:
                have_k = 1
                rec[col]['list'].remove(v)
        if not have_k:
            return {'res':'user_no_%s' % col}
        conn = mysql()       
        photo_rec = json_encode(rec)          
        #sql = "UPDATE t_user_record SET photo_rec = '%s' WHERE uid =%d " %(conn.escape_string(photo_rec),uid)
        conn.upData("t_user_record", {"photo_rec":photo_rec}, " WHERE uid = %d" % uid,asyn=True)
        
        if col=='p':            
            util.CountUserUtil.judgeAndEditExt('delete_album_photo', request, uid, "user_delete_photo")
            
            url = const.ConfigDelPhotoUrl + '?uid=%s&rec_id=%s'%(uid,rec_id)
            util.asynOpenUrl(url);          
           
        return {'res':True}
    
    
    #查询某用户（当天）记录    
    @staticmethod
    def get_user_log(list, uid=None, today=None, groupby=None, desc='asc'):
        
        tmpList = list
        nowtime = time.strftime('%Y-%m-%d')
        if tmpList:            
            for v in tmpList:
                if uid:
                    if v['uid'] == uid:                        
                        tmpList.remove(v)
                        continue
                if today:
                    if str(v['timeline'])[0:10] == nowtime:
                        tmpList.remove(v)
            if groupby:
                g_list = {}
                for v in tmpList:
                    g_list[v[groupby]] = v
                tmpList = []
                for k, v in g_list.iteritems():
                    tmpList.append(v)                        
                 
        tmpList.sort(lambda x, y: cmp(x['rec_id'], y['rec_id']))     
        tmpList = sorted(tmpList, key=lambda x:x['rec_id'])  
        if desc == 'desc':
            l = []
            for v in reversed(tmpList):
                l.append(v)
            tmpList = l 
        return tmpList
    
    #设置封面
    @staticmethod
    def set_cover(request, data):
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}
        uid = user.m_userinfo['uid']
        photo_id = data['photo_id']
        album_id = data['album_id']
        userinfo = UserManager.get_userinfo_record(uid, 'photo_rec')
        if not userinfo['photo_rec']:
            return {'res':'user_no_a'}
        rec = json_decode(userinfo['photo_rec'])
        if not rec.has_key('a'):
            return {'res':'user_no_a'}
        if not rec.has_key('p'):
            return {'res':'user_no_p'}
        if not store.get_my_goods_info_by_rec_id(photo_id, rec['p']['list']):
            return {'res':'user_no_p'}
        album = store.get_my_goods_info_by_rec_id(album_id, rec['a']['list'])
        if not album:
            return {'res':'user_no_a'}        
        rec['a']['list'].remove(album)
        album['cover'] = photo_id
        rec['a']['list'].append(album)
        conn = mysql()
        udata = {'photo_rec':json_encode(rec)}
        conn.upData('t_user_record', udata, "WHERE uid = %d" % uid,asyn=True) 
        return {"res":True}
    
    #发送好友印象
    @staticmethod
    def send_impression(request,data):
        cmd = "send_impression"
        tmpUser = UserManager.get_user_by_request(request)
        if not tmpUser:
            return {'res':'user_is_null'}
        
        userinfo = tmpUser.m_userinfo
        uid = tmpUser.getUID()
        
        toUid = data.get('uid')
        content = data.get('content')
        
        if not toUid or not content:
            return {'res':'pam_err'}
        
        #评论好友印象给评论者增减数值
        if not util.CountUserUtil.judgeAndEditExt(cmd, request, uid, "comment_impression"):
            return {'res':'not_courage'}
        
        #给被评论者增减数值
        #util.CountUserUtil.judgeAndEditExt(cmd, request, toUid, "commented_impression", False)
        

			
        new_dic = {'content':content}
        roomer = UserManager.get_userinfo_record(toUid, 'uid,nickname,impression')
        res = UserManager.set_user_rec( userinfo, roomer,'impression', const.Config_impression_max(), new_dic)#设置我的访问记录
        
        return res
    
    
    @staticmethod
    def get_impression(request,data):  
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}  
        toUid = data.get('uid')
        roomer = UserManager.get_userinfo_record(toUid, 'uid,nickname,impression')
        tmpImpression = roomer['impression']
        if not tmpImpression:
            return {"res":True, "list":[]}
        tmpImpression = json_decode(tmpImpression)
        if not tmpImpression:
            return {"res":True, "list":[]}
        
        return {"res":True, "list":tmpImpression.get('log')}
        
        
    #设置留言已读    
    @staticmethod
    def set_msg_is_got(request, data, stype='set'):
        tmpUser = UserManager.get_user_by_request(request)
        if not tmpUser:
            return {'res':'user_is_null'}
        uid = tmpUser.m_userinfo['uid']
        rec_id = data['rec_id']
        userinfo = UserManager.get_userinfo_record(uid, 'guest_leaveword')
        if not userinfo['guest_leaveword']:
            return {'res':'no_record'}
        guest_leaveword = json_decode(userinfo['guest_leaveword'])
        if not guest_leaveword.has_key('log'):
            return {'res':'no_record'}
        tmpList = guest_leaveword['log']
        tmpRec = store.get_my_goods_info_by_rec_id(rec_id, tmpList)               
        if not tmpRec:
            return {'res':'no_record'}
        tmpList.remove(tmpRec)
        if stype == 'set':
            tmpRec['got'] = 1
            tmpList.append(tmpRec) 
        else:           
            tmpPresentGoods =  tmpRec.get('id')
            if tmpPresentGoods:
                for v in tmpPresentGoods:
                    if v.get('got')==0:
                        store.deUserGoods(tmpUser,v.get('rec_id'),v.get('id'))  
            
        guest_leaveword['log'] = tmpList
        conn = mysql()
        udata = {'guest_leaveword':json_encode(guest_leaveword)}
        conn.upData('t_user_record', udata, "WHERE uid = %d" % uid) 
        
        return {"res":True, "rec_id":rec_id}
    
    
    #提取礼品
    @staticmethod
    def get_present(request, data):
        user = UserManager.get_user_by_request(request)
        if not user:
            return {'res':'user_is_null'}
        
        rec_id = data['rec_id']
        get_id = data['id']
        uid = user.m_userinfo['uid']
        #得到我的礼品列表
        tmpMyPresent = user.m_userinfo['my_present']
        
        if not tmpMyPresent:
            
            return {'res':'not_goods'}
        
        #查看我的礼品列表对应商品大小礼品的数量是否大于礼品架上的数量限制，如果超过了，则不进行任何操作，没超过则把当前的礼品更新为已领取
        i=0
        for v in get_id:
            goods_info = store.get_goods_info(v['id'])    
            type_1 = goods_info['type_1']
            type_2 = goods_info['type_2']
            type_3 = goods_info['type_3']
            if not tmpMyPresent.has_key(type_2):
               
                return {'res':'not_goods'}
            if not tmpMyPresent[type_2].has_key(type_3):
               
                return {'res':'not_goods'}
            #当前商品类别列表
            tmpThisGoods = tmpMyPresent[type_2][type_3]['info']
            #取得当前 大/小 礼品 总数量
            tmpTotalPresentNums = store.get_my_goods_nums(tmpMyPresent, {"z_1":goods_info['z_1'],"got":1})
            #如果是小礼品
            if goods_info['z_1'] == 0:
                if (tmpTotalPresentNums + i + 1) > const.Config_small_present_notice_nums():
                    return {'res':'must_sell_present'}
            #如果是大礼品
            if goods_info['z_1'] == 1:
                if (tmpTotalPresentNums + i + 1) > const.Config_big_present_notice_nums():
                    return {'res':'must_sell_present'}
            #把当前礼品在我的礼品列表中标识为 已经领取
            for vv in tmpThisGoods:               
                if vv['id'] == v['id'] and v.get('rec_id')==vv.get('rec_id') and vv.get('rec_id')!=0 and vv.get('got')==0:
                  
                    tmpThisGoods.remove(vv)
                    vv['got']=1
                    tmpMyPresent[type_2][type_3]['info'].append(vv)
                    
            i+=1
            
        conn = mysql()                
        conn.upData('t_user_data',{'my_present':json_encode(tmpMyPresent)},"WHERE uid = %d" % uid,asyn=True)          
        UserManager.update_user(uid, {'my_present':tmpMyPresent})
        #取得我所有的礼品留言记录
        userinfo = UserManager.get_userinfo_record(uid, 'guest_leaveword')
        if not userinfo['guest_leaveword']:
            return {'res':'no_record'}
        guest_leaveword = json_decode(userinfo['guest_leaveword'])
        if not guest_leaveword.has_key('log'):
            return {'res':'no_record'}
        tmpList = guest_leaveword['log']
        
        #取得当前记录ID的留言记录
        tmpRec = store.get_my_goods_info_by_rec_id(rec_id, tmpList)               
        if not tmpRec:
            return {'res':'no_record'}
        
        #取得当前记录的id
        tmpId = tmpRec.get('id')
        if not tmpId:
            return {'res':'not_goods'}
        
        #从所有列表中删除当前记录，并更新当前记录值，最后再把当前记录加到所有记录中
        tmpList.remove(tmpRec)
        
        newTmpId = []
        
        #得到需要更改状态的礼品列表，并保存
        for v in tmpId:
            for vv in get_id:                
                if v.get('id') == vv['id'] and v['rec_id']==vv['rec_id']:                
                    v['got'] = 1
            newTmpId.append(v)
        
        tmpRec['id'] = newTmpId
        
        tmpList.append(tmpRec)
        
        guest_leaveword['log'] = tmpList
        
        udata = {'guest_leaveword':json_encode(guest_leaveword)}
        conn.upData('t_user_record', udata, "WHERE uid = %d" % uid)
        return {"res":True}
    
    